//
//  JSExpListController.swift
//  fho
//
//  Created by 郭颢源 on 2021/4/10.
//

import UIKit

/// 查快递
class JSExpListController: UIViewController,UIGestureRecognizerDelegate {
    //存放数据的数组
    lazy var dataArray:[MyCarGroupModel] = {
        
        var _dataArray = Array<MyCarGroupModel>()
        return _dataArray
        
    }()
    
    private lazy var cellId = "MyCarCell"
    fileprivate lazy var tableView : UITableView = {
        let tv = UITableView(frame: .zero, style: .plain)
        tv.register(MyCarCell.self, forCellReuseIdentifier: cellId)//注册cell
        
        tv.delegate = self
        tv.dataSource = self
        
        tv.separatorStyle = .none//分割线
        tv.estimatedRowHeight = 0//预设行高
        tv.estimatedSectionFooterHeight = 0//预设分区头高度
        tv.estimatedSectionHeaderHeight = 0
        //        tv.backgroundColor = UIColor.white
        
        if #available(iOS 11.0, *) {
            tv.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        }
        return tv
    }()
    //自定义右侧view
    //    var myView:MyCarsView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.edgesForExtendedLayout = .init()
        self.title = "查快递"
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }
 

        // Do any additional setup after loading the view.
        loadData()
    }

    func setupRightIndexView() {
        
        var array = Array<Any>()
        for model in self.dataArray {
            
            if model.title.contains("当前常用") {
                array.append("🌟")
            }else
            {
                array.append(model.title)
            }
        }
        
        
        let singleH:CGFloat = 20
        var section:Int = 0
        
        let myView:MyCarsView = MyCarsView().initWithDataArray(array, singleH: singleH) { [ self] (tag) in
            if tag < 0{
                section = 0
            }else if tag > dataArray.count-1{
                section = dataArray.count-1
            }else
            {
                section = tag
            }
            
            let indexPath:IndexPath = IndexPath(row: 0, section: section)
            tableView.scrollToRow(at: indexPath, at: .top, animated: true)
        }
        
        view.addSubview(myView)
        
        
        myView.snp.makeConstraints { (make) in
            make.centerY.equalTo(tableView.snp.centerY)
            make.right.equalTo(0)
            make.width.equalTo(50)
            make.height.equalTo(Int(singleH)*dataArray.count)
        }
        
        
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}


extension JSExpListController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section==0 {
            return 1
        }
        let model:MyCarGroupModel = dataArray[section]
        return model.cars.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section==0 {
            
            let cell = tableView.dequeueReusableCell(for: JSUsedCell.self)
            //设置单元格标题
            let groupModel: MyCarGroupModel = dataArray[indexPath.section]
            
            cell.tui = groupModel.cars
            return cell
        }
        let cell = tableView.dequeueReusableCell(for: MyCarCell.self)
        //设置单元格标题
        let groupModel: MyCarGroupModel = dataArray[indexPath.section]
        let model:JSListModel = groupModel.cars[indexPath.row] as! JSListModel
        cell.model = model
        
        return cell
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let model: MyCarGroupModel = dataArray[section]
        return model.title
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.tintColor = .clear
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.textColor = .systemOrange
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 180
        }
        return 55
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)
        let groupModel: MyCarGroupModel = dataArray[indexPath.section]
        let model:JSListModel = groupModel.cars[indexPath.row] as! JSListModel
        let controller = JSExpressQueryController()
        controller.data = model
        navigationController?.pushViewController(controller, animated: true)
    }
}

extension JSExpListController
{
    
    /// loadData
    func loadData() {
        let viewModel = BiloginViewModel()
        
        
//        let provider = MoyaProvider<BiLoginAPi>(plugins: [networkPlugin])
//        provider.request(.realtimeWeather(cityId: "1")) { (result) in
//            //            print(result)
//            if case .success(let response) = result {
//                // 解析数据
//                let jsonDic = try! response.mapJSON() as! NSDictionary
//                print(jsonDic)
//                let model = try! response.map(BiModel.self)
//                print(model.msg!)
//            }
//        }
        //        let provider = MoyaProvider<NetworkAPI>(plugins: [networkPlugin])
        ////        provider.plugins = [networkPlugin]
        //
        //        provider.request(.realtimeWeather(cityId: "")) { (result) in
        //
        //        }
        //
        //
        //
        //            NetworkProvider.request(NetworkAPI.realtimeWeather(cityId: "101040100")) { result in
        //                if case .success(let response) = result {
        //                   // 解析数据
        //                    let jsonDic = try! response.mapJSON() as! NSDictionary
        //                    print(jsonDic)
        //                }
        //            }
        
        
        
        
        JSShowMessage.showTipMsg("asdf", time: 1)
//        "https://zhizhu.56114.com/lis/danhao/index1?type=1" // type 1：物流，2：快递
        let params = [
            "type":"2"
        ]
                HttpRequest.GET("https://zhizhu.56114.com/lis/danhao/index1", params) { [self] (result:BaseResponse<JSDataModel>) in
                    
                    if let tui : [JSTuiModel] = result.data?.tui {
                        let groupModel = MyCarGroupModel()
                        groupModel.cars = tui
                        groupModel.title = "当前常用"
                        self.dataArray.append(groupModel)
                        
                    }
                    
                    guard let list: [JSListModel] = result.data?.list else {
                        return
                    }
                    let keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        
                    for key in keys{
                        //过滤首字母
                       let bb = list.filter({ $0.zm == String(key) })
                        if bb.count>0 {
                            let groupModel = MyCarGroupModel()
                            groupModel.cars = bb
                            groupModel.title = String(key)
                            self.dataArray.append(groupModel)
                        }
                    }
                    
                    setupRightIndexView()
                    self.tableView.reloadData()
                }
        
    }
    func setData(){
        
    }
}
